//
//  WidgetTemplateFinder.m
//  WebClipper
//
//  Created by Daniel Braun on 25/04/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "WidgetTemplateFinder.h"
#import "WidgetTemplate.h"


@implementation WidgetTemplateFinder

- (id) init {
	self = [super init];
	if (self != nil) {
	}
	return self;
}

- (void) dealloc {
	[w release];
	[super dealloc];
}

- (NSArray *) widgets
{
	if (!w) [self _scanForWidgets];
	return w;
}

- (IBAction) reload:(id) sender
{
	[self willChangeValueForKey:@"widgets"];
	[self _scanForWidgets];
	[self didChangeValueForKey:@"widgets"];
}


- (void) _scanForWidgetsInDir:(NSString *)wp user:(BOOL)user
{
	NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] 
		enumeratorAtPath:wp];
	NSString *wname=nil;
	while ((wname=[direnum nextObject])) {
		BOOL isProj=NO;
		NSLog(@"got %@\n", wname);
		[direnum skipDescendents];
		if ([wname hasPrefix:@"."]) continue;
		if ([wname hasSuffix:@".wdgt"]) {
			isProj=NO;
		} else if ([wname hasSuffix:@".wdgtproj"]) {
			isProj=YES;
		} else continue;
		WidgetTemplate *wt=[[[WidgetTemplate alloc]initWithPath:
			[NSString stringWithFormat:@"%@/%@", wp, wname]]autorelease];
		if (!wt) continue;
		wt->isUser=user;
		wt->isWdgtProj=isProj;
		[w addObject:wt];
	}
}

- (NSString *) applicationSupportFolder 
{
	NSString *applicationSupportFolder = nil;
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
	if ( [paths count] == 0 ) {
		NSRunAlertPanel(@"Alert", @"Can't find application support folder", @"Quit", nil, nil);
		[[NSApplication sharedApplication] terminate:self];
		return nil;
	} else {
		applicationSupportFolder = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"WebExtractor"];
	}
	//create it if needed
	NSFileManager *fileManager = [NSFileManager defaultManager];
	if ( ![fileManager fileExistsAtPath:applicationSupportFolder isDirectory:NULL] ) {
		[fileManager createDirectoryAtPath:applicationSupportFolder attributes:nil];
	}
	return applicationSupportFolder;
}

- (NSString *) widgetTemplatesFolder
{
	NSString *widgetTemplatesFolder;
	widgetTemplatesFolder=[[self applicationSupportFolder] stringByAppendingPathComponent:@"widgetTemplates"];
	if (!widgetTemplatesFolder) return nil;
	//create it if needed
	NSFileManager *fileManager = [NSFileManager defaultManager];
	if ( ![fileManager fileExistsAtPath:widgetTemplatesFolder isDirectory:NULL] ) {
		[fileManager createDirectoryAtPath:widgetTemplatesFolder attributes:nil];
	}
	return widgetTemplatesFolder;
}

- (void) _scanForWidgets
{
	[w release];
	w=[[NSMutableArray arrayWithCapacity:10]retain];
	// bundle templates
	NSString *wp=[[NSBundle mainBundle]pathForResource:@"widgets"
						    ofType:@""];
	if (!wp) return;
	[self _scanForWidgetsInDir:wp user:NO];
	wp=[self widgetTemplatesFolder];
	NSLog(@"user templates : %@\n", wp);
	[self _scanForWidgetsInDir:wp user:YES];
}


- (BOOL) dropFile:(NSString *)sourceWidget
{
	NSLog(@"dropped %@\n", sourceWidget);
	NSString *widgetName=[[sourceWidget pathComponents]lastObject];
	if (!widgetName) return NO;
	NSString *destPath=[self widgetTemplatesFolder];
	destPath=[destPath stringByAppendingPathComponent:widgetName];
	NSAssert([destPath isKindOfClass:[NSString class]], @"should be a string");
	NSLog(@"dropped %@, copy to %@\n", sourceWidget, destPath);

	NSFileManager *m=[NSFileManager defaultManager];
	
	//return NO;
	if ([m fileExistsAtPath:destPath]) {
		BOOL result = NSRunAlertPanel(@"WebExtractor", 
					      @"File %@ already exist.", @"Overwrite", @"Stop",  NULL,
					      destPath,
					      nil);
		
		if (result != NSAlertDefaultReturn) return NO;
		[m removeFileAtPath:destPath handler:self];
	}
	BOOL ok=[m copyPath:sourceWidget toPath:destPath handler:self];
	if (!ok) return NO;
	// cleanup widget
	
	return ok;
}

- (void)fileManager:(NSFileManager *)manager willProcessPath:(NSString *)path
{
}
-(BOOL)fileManager:(NSFileManager *)manager
        shouldProceedAfterError:(NSDictionary *)errorInfo
{
	int result;
	result = NSRunAlertPanel(@"WebExtractor", @"File  operation error:  %@ with file: %@", @"Proceed", @"Stop",  NULL,
				 [errorInfo objectForKey:@"Error"],
				 [errorInfo objectForKey:@"Path"]);
	
	if (result == NSAlertDefaultReturn) return YES;
	else return NO;
}



@end
